//
//  StatusViewModel.swift
//  XinLangWeibo10
//
//  Created by 白利兵 on 15/10/19.
//  Copyright © 2015年 itheima. All rights reserved.
//

import UIKit
import SDWebImage
class StatusListViewModel {
    // 下拉刷新微博个数
    var pullDownCount = 0
    
    // 微博模型数组
    lazy var statusList = [StatusViewModel]()
    
    // 发送网络请求数据
    func loadStatusList(isPullUp isPullUp: Bool, finished: (isSuccessed: Bool) -> ()) {
    // 判断是上拉刷新和下拉刷新
        let since_id = isPullUp ? 0 : statusList.first?.status.id ?? 0
        let max_id = isPullUp ?  (statusList.last?.status.id ?? 0) : 0
        // 加载微博数据
        StatusDAL.loadStatusData(since_id, max_id: max_id) { (array) -> () in
            guard let statusArray = array else {
                print("网络夹杂出错")
                return
            }
            //定义一个可变数组
            var arrayM = [StatusViewModel]()
            // 遍历数组
            for dict in statusArray {
                // 把模型数组加到数组中
                arrayM.append(StatusViewModel(status: Status(dict: dict)))
            }
            //self.statusList = arrayM;
            // 如果是上拉刷新，则数据拼接到后面
            if max_id > 0  {
                self.statusList = self.statusList + arrayM
            }
                // 下拉刷新，数据拼接到前面
            else {
                self.statusList = arrayM + self.statusList
            }
            print("缓存到了\(self.statusList.count)张图片")
            // 缓存单张图片
            self.downLoadImage(self.statusList, finished: finished)
        }
    }
     //增加调度组，缓存单张图片
    private func downLoadImage(VmArray: [StatusViewModel], finished: (isSuccessed: Bool) -> ()){
        // 创建调度组
        let group = dispatch_group_create()
        var dataLength = 0
        // 遍历视图模型数组
        for viewModel in VmArray
        {
            print("picCount = \(viewModel.thumbnail_pic?.count)")
            // 判断是否是单张图
            if viewModel.thumbnail_pic?.count != 1 {
                continue // 跳出本次循环
            }
            let url = viewModel.thumbnail_pic?[0]
            // 进入调度组
            dispatch_group_enter(group)
            // 下载图片
            SDWebImageManager.sharedManager().downloadImageWithURL(url,
                options: [],
                progress: nil) { (image, error, _, _, _) in
                    
                    if let img = image,
                        data = UIImagePNGRepresentation(img) {
                            print("data.length=\(data.length)")
                            dataLength += data.length
                            //print(dataLength)
                    }
                    
                    dispatch_group_leave(group)
            }
        }
        // 监听调度组是否完成
        dispatch_group_notify(group, dispatch_get_main_queue(), { () -> Void in
            print("缓存图像完成 \(dataLength / 1024) K")
            // 成功回调
            finished(isSuccessed: true)
        })
    }
}


